const qcloud = require('../vendor/wafer2-client-sdk/index')
const config = require('../config.js')
const service = config.service

const sharedService = {
  onShareAppMessage: function(options, callback){
    const that = this
    return {
      title: '口算天才',
      path: 'pages/index/index',
      imageUrl: '../images/img_share.png',
      success: function (res) {
        // console.log(res.shareTickets[0])
        that.getSharedInfo(res, function() {
          if (callback) {
            callback();
          }
        })
      },
      fail: function (res) {
        // 分享失败
        console.log(res)
      }
    }
  },
  getSharedInfo: function(res, callback) {
    const that = this
    if (res && res.errMsg === 'shareAppMessage:ok') {
      if (res.shareTickets && res.shareTickets[0]) {
        const shareTicket = res.shareTickets[0]
        wx.getShareInfo({
          shareTicket: res.shareTickets[0],
          success: function (res) {
            that.updateSharedGroup(res, callback)
          },
          fail: function (res) {
            console.log('shared fail', res)
          },
          complete: function (res) {
            console.log('shared complete', res)
          }
        })
      }
    }
  },

  updateSharedGroup: function(res, callback) {
    const userInfo = getApp().globalData.userInfo
    qcloud.request({
      url: service.sharedUrl,
      method: 'post',
      data: {
        open_id: userInfo.openId,
        data: res
      },
      success: function(response) {
        if (callback) {
          callback();
        }
      }
    })
  }
}

module.exports = sharedService
